package cn.bx.bid.ctrl;

import cn.bx.bid.entity.Page;
import cn.bx.bid.entity.User;
import cn.bx.bid.entity.Userrole;
import cn.bx.bid.service.RoleService;
import cn.bx.bid.service.UserService;
import cn.bx.bid.util.AjaxResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Controller
public class UserController {
    @Resource
    UserService userService;
@Resource
RoleService roleService;
@PostMapping(value ="login",produces = "application/json;charset=utf-8")
@ResponseBody
public AjaxResult login(HttpServletRequest request, @RequestParam(name = "username",required = true,defaultValue = "") String u,
                        @RequestParam(name = "password",required = true,defaultValue = "") String p){
    User user = this.userService.login(u,p);
    if (user!=null){
        return AjaxResult.success("登录成功",user);

    }
    return AjaxResult.error("登录失败");
}
//模糊查询及全部
    @GetMapping(value = "usersearch",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Page<User> search(@RequestParam(name = "page", defaultValue = "1")
                                     int pageNo, @RequestParam(name = "limit", defaultValue = "10")
                                     int limit, @RequestParam(name = "name", required = false) String name,
                             @RequestParam(name = "startDate", required = false) Date start,
                             @RequestParam(name = "endDate", required = false) Date end) {

        Page<User> page =userService.paging(pageNo, limit, name, start, end);
        return page;
    }

//     @GetMapping("user-update-{id}")
//    public String toUpdate(@PathVariable("id") long id, Model m){
//        User u=this.userService.get(id);
//        m.addAttribute("user",u);//也可以带对象给视图
//        return "user-update";
//    }
//    @PostMapping("userupdate")
//    public String updent(@ModelAttribute("u") User user, HttpServletRequest req) {
//
//        int r = userService.update(user);
//        req.setAttribute("msg", r > 0 ? "修改成功" : "修改失败");
//        return "regsuccess";
//    }
    //增加
@RequestMapping(value = "userAdd",produces = "application/json;charset=utf-8")
@ResponseBody
public AjaxResult register(HttpServletRequest request, @ModelAttribute("u") User user){

    int r = this.userService.add(user);
    if (r>0){
        return AjaxResult.success("注册成功！");
    }
    return AjaxResult.error("注册失败！");
}
//获得id修改
    @GetMapping(value = "userGet",produces = "application/json;charset=utf-8")
    @ResponseBody
    public AjaxResult toupdate(@RequestParam("id")Long id){
        User user = this.userService.get(id);
        return user!=null? AjaxResult.success("成功获取对象",user): AjaxResult.error("获取对象失败");
    }

//修改
@PostMapping(value = "userUpdate",produces = "application/json;charset=utf-8")
@ResponseBody
public AjaxResult update(@ModelAttribute("userUpdate") User u){
    int r = this.userService.update(u);
    return r>0? AjaxResult.success("修改成功"): AjaxResult.error("修改失败");
}

////修改密码
//   @GetMapping(value = "userUpdatepass",produces = "application/json;charset=utf-8")
//    @ResponseBody
//    public AjaxResult updatepass(@ModelAttribute("userUpdatepass")User u){
//       int r = this.userService.updatepassword(u);
//        return r>0?AjaxResult.success("修改密码成功"):AjaxResult.error("修改密码失败");
//    }

//下拉框
    @RequestMapping(value = "findRoles", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String findRoles() {
        List<Userrole> li = roleService.findALL();
        String str = JSON.toJSONStringWithDateFormat(li, "yyyy-MM-dd");
        return str;
    }

//批量删除
@GetMapping(value = "userdel",produces = "application/json;charset=utf-8")
@ResponseBody
  public AjaxResult batchDel(@RequestParam("ids[]") long[] ids){
        int r= this.userService.batchDel(ids);
    if (r==1){
        return AjaxResult.success("删除成功");
    }
    return AjaxResult.error("删除失败");
}
    //验证用户名是否重复
    @RequestMapping(value = "checkUserNameRepeat", produces = "application/json;charset=utf-8")
    @ResponseBody
    public AjaxResult checkUserNameRepeat(@RequestParam("userName") String name, @RequestParam(name="id",required = false) Long id) {

        boolean r = this.userService.checkUserNameRepeat(id, name);

        if (r==true){
            return AjaxResult.success("用户名可用");
        }
        return AjaxResult.error("用户名重名！");
    }



    //日期转换器
    @InitBinder//从请求到Controller
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        // true:允许输入空值，false:不能为空值
    }
    //局部，只能处理UserController中的异常
    @ExceptionHandler
    public String handlerException(Exception e){
        e.printStackTrace();//Log4j
        return "error";
    }
}






